package br.com.canvasForAll.ws.resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

import br.com.canvasForAll.model.entity.Usuario;
import br.com.canvasForAll.model.repository.UsuarioRepository;

@Path("teste")
public class TesteWS {
	
	@EJB
	private UsuarioRepository usuarioRepository;
	
	@GET
	@Path("{id_user}")
	@Produces(MediaType.APPLICATION_JSON)
	public Usuario buscarUserId(@PathParam("id_user") Long idUser) {
		try{
			Usuario u = usuarioRepository.obterId(idUser);
			return u;

		} catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public List<Usuario> buscarUsers() throws Exception {
		List<Usuario> users = usuarioRepository.obterTodos();
		return users;

	}
	
	@POST
	@Path("/addUser/{id_user}")
	@Consumes(MediaType.APPLICATION_JSON)
	public void addUsuario(@PathParam ("id_user") String u, Usuario user) throws Exception {
		user.setId(Long.valueOf(u));
		user.setDataCriacao(new Date());
		user.setDataUltimaAtualizacao(new Date());
		usuarioRepository.criar(user);

	}
	
	private final String UPLOADED_FILE_PATH = System.getProperty("user.home") + "/workspace/canvasForAll-ics_WEB/WebContent/resources/files/";
	
	@POST
	@Path("/upload-file")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public Response uploadFile(MultipartFormDataInput input) throws IOException {
		String fileName = "";
		
		Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
		List<InputPart> inputParts = uploadForm.get("file");
		
		for(InputPart ip : inputParts){
			try{
				MultivaluedMap<String, String> header = ip.getHeaders();
				fileName = getFileName(header);
				InputStream inputStream = ip.getBody(InputStream.class, null);
				
				byte[] bytes = IOUtils.toByteArray(inputStream);
				
				fileName = UPLOADED_FILE_PATH + fileName;
				writeFile(bytes, fileName);

				System.out.println("DONE!!!");
				
			} catch (IOException e){
				e.printStackTrace();
			}
		}
		
		return Response.status(200).entity("uploadFile is called, Uploaded file name : " + fileName).build();

	}
	
	private String getFileName(MultivaluedMap<String, String> header){
		String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
		
		for(String filename : contentDisposition){
			if((filename.trim().startsWith("filename"))){
				String[] name = filename.split("=");
				String finalFileName = name[1].trim().replaceAll("\"", "");
				return finalFileName;
			}
			
		}
		return "unknown";
	}
	
	private void writeFile(byte[] content, String filename) throws IOException {
		File file = new File(filename);
 
		if (!file.exists()) {
			file.createNewFile();
		}
 
		FileOutputStream fop = new FileOutputStream(file);
 
		fop.write(content);
		fop.flush();
		fop.close();
 
	}
}
